<?php
/**
 * Created by PhpStorm.
 * User: DaibiDaddy
 * Date: 2016/5/24
 * Time: 17:14
 */

namespace App\Base;

use App\Entity\User;
use App\Model\LazyCommon\UserModel;
use Symfony\Component\HttpFoundation\Request;

class BaseController4App extends BaseController {


    public $data = [];

    public function __construct()
    {
        parent::__construct();
        $request = Request::createFromGlobals();
        $token = $request->headers->get("token");
        $nowtime = $request->headers->get("nowtime");
        if (md5($nowtime.BaseConfig::__VI__) != $token) {
            echo time();
            die("I KNOW U");
        }
    }

    public function setError($str,$url = "",$delay = 0)
    {
        $this->data["error"] = $str;
        $this->data["redirect"] = $url;
        $this->data["delay"] = $delay;
    }

    /**
     * @param $phone
     * @return User|bool
     */
    public function checkPhoneIsUsed($phone)
    {
        $Model = new UserModel($this->getDoctrine());
        $data = $Model->getByPhone($phone);
        if ($data) {
            //已经注册
            return $data;
        } else {
            //可以使用
            return false;
        }
    }

    public function needToBeLogin($messge = "")
    {

        $access_token = (new BaseCache())->getUserAccessToken(Request::createFromGlobals());
        header('content-type:application/json');
        header('charset:utf8');
        header("HTTP/1.1 203 Non-Authoritative Information");
        header('access-token:'.$access_token);
        $s = 203;
        $i = "正在进行身份验证";
        $d = $messge;
        $re = array(
            "s"    => $s,
            "i"    => $i,
            "d"    => $d,
//            "at"    => $access_token,
        );
        die(json_encode($re));
//        $url = $this->generateUrl("UserAppHomeIndex");
//        header('Location:'.$url);
//        die;
    }

    public function isUser()
    {
        $tokenData = $this->getTokenData();
        if ($tokenData && isset($tokenData["role"])) {
            $roles = $tokenData["role"];
        }else{
            return false;
        }
        if (is_array($roles) && in_array("ROLE_USER",$roles)) {
            return $tokenData["id"];
        } else {
            return false;
        }
    }

    public function needToBeUser()
    {
        if ($uid = $this->isUser()) {
            $request = Request::createFromGlobals();
            $UserModel = new UserModel($this->getDoctrine());
            $user = $UserModel->getUserById($uid);
            if (!$user) {
                $this->needToBeLogin("user has been removed");
            }
            if ($user->getPasswordPay() != $request->headers->get("sessId")) {
                $this->needToBeLogin("sessId does not match");
            }
            return $uid;
        } else {
            $this->needToBeLogin("user not found");
        }
    }


    public function getOpenid()
    {
        return $this->getSessionData("openid");
    }

}
